import {systemDeleteFile, systemUpload} from "@/util/Api";
import {uuid} from "@/util/global";

/**
 * 封装AntD 中的 Upload组件 下的 customRequest回调方法
 * （动态stateKey）
 * @param that
 * @param option
 * @param keyStr
 */
export function commonUploadByKey(that, option, keyStr) {
    const {file} = option;
    let uid = uuid();
    let imgItem = {
        uid,
        name: file.name,
        status: 'uploading',
        url: '',
        percent: 99, //100表示上传完成
    };
    let state = that.state;
    state[keyStr].push(imgItem);
    that.setState(state)
    const formData = new FormData();
    formData.append('file', option.file);
    systemUpload(formData).then(r => {
        if (r.success) {
            let state = that.state;
            state[keyStr].forEach(item => {
                if (item.uid === uid) {
                    item.url = `${r.data}`
                    item.imgUrl = `${r.data}`
                    item.status = 'done';
                }
            })
            that.setState(state)
        }
    })
}

/**
 * 封装AntD 中的 Upload组件 下的 customRequest回调方法
 * @param that
 * @param option
 */
export function commonUpload(that, option) {
    const {file} = option;
    let uid = uuid();
    let imgItem = {
        uid,
        name: file.name,
        status: 'uploading',
        url: '',
        percent: 99, //100表示上传完成
    };
    let {fileItems} = that.state;
    fileItems.push(imgItem);
    that.setState({
        fileItems: fileItems
    })
    const formData = new FormData();
    formData.append('file', option.file);
    systemUpload(formData).then(r => {
        if (r.success) {
            let {fileItems} = that.state;
            fileItems.forEach(item => {
                if (item.uid === uid) {
                    item.url = `${r.data}`
                    item.imgUrl = `${r.data}`
                    item.status = 'done';
                }
            })
            that.setState({
                fileItems
            })
        }
    })
}

/**
 * 封装AntD 中的 Upload组件 下的 onRemove回调方法
 * @param that
 * @param file
 */

export function commonRemoveFile(that, file) {
    return new Promise((resolve, reject) => {
        systemDeleteFile({path: file.imgUrl})
            .then(res => {
                resolve(res.success);
            })
    }).then(r => {
        if (r) {
            const removed = that.state.fileItems.filter(item => item.uid !== file.uid);
            that.setState({
                fileItems: removed
            })
        }
    });
}
